<template>
  <view>
    <!-- 我的
    {{ count }} -->
    <view class="search">
      <u-search
        placeholder="请输入商品名称"
        v-model="inp"
        @custom="handlerAdd"
      ></u-search>
    </view>
    <view class="info">
      <u-table>
        <u-tr>
          <u-th>商品</u-th>
          <u-th>数量</u-th>
        </u-tr>
        <u-tr v-for="(item, index) in list" :key="item.name">
          <u-td>{{ item.name }}</u-td>
          <u-td>
            <view class="count u-flex">
              <button @click="handlerCount(+1, index)">+</button>
              <view>{{ item.count }}</view>
              <button @click="handlerCount(-1, index)">-</button>
            </view>
          </u-td>
        </u-tr>
      </u-table>
    </view>
  </view>
</template>

<script>
export default {
  data() {
    return {
      // 输入框的值
      inp: "",
      // list: [],
    };
  },
  computed: {
    list() {
      // return (this.list = this.$store.state.list);
      return this.$store.state.list;
    },
  },
  methods: {
    handlerAdd() {
      // console.log(this.inp);
      // 搜索里面是否已经添加过相同的商品
      const index = this.list.findIndex((v) => v.name === this.inp);
      // 重新定义list列表
      const list = this.list;
      if (index === -1) {
        // this.list.push({ name: this.inp, count: 1 });
        list.push({ name: this.inp, count: 1 });
      } else {
        list[index].count++;
      }
      this.$store.commit("setList", list);
    },
    handlerCount(num, index) {
      const list = this.list;
      console.log(num, index);
      // this.list[index].count += num;
      list[index].count += num;
      // 通知仓库进行变化
      this.$store.commit("setList", list);
    },
  },
  // computed: {
  //   count() {
  //     return this.$store.state.count;
  //   },
  // },
};
</script>

<style>
</style>